package com.yanqu.road.server.cmd.banquet;

import com.yanqu.road.entity.banquet.CrossPartyRelationship;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.banquet.BanquetProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.banquet.CrossPartyMgr;
import com.yanqu.road.server.pb.banquet.CrossBanquetPb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.Protocol;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Cmd(code = CrossProtocol.C_CROSS_BANQUET_USER_RELATIONSHIP, desc = "")
public class CrossBanquetRelationshipCmd extends CrossCommand {

    private long userId;

    //正在开的跨服宴会冲榜活动的开始时间和结束时间
    private long beginShowTime;
    private long endShowTime;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        BanquetProto.CrossBanquetUserRelationshipReqMsg reqMsg = BanquetProto.CrossBanquetUserRelationshipReqMsg.parseFrom(packet.getBytes());
        beginShowTime = reqMsg.getBeginShowTime() * 1000;
        endShowTime = reqMsg.getEndShowTime() * 1000;
        userId = packet.getPlayerId();
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {
        Map<Long, CrossPartyRelationship> recordMap = CrossPartyMgr.getPartyRelationship(userId, 2, beginShowTime);
        List<CrossPartyRelationship> recordList = new ArrayList<>(recordMap.values());
        recordList.sort((o1, o2) -> {
            if (o1.getTo() + o1.getFrom() == o2.getTo() + o2.getFrom()) {
                return 0;
            }
            if (o1.getTo() + o1.getFrom() >= o2.getTo() + o2.getFrom()) {
                return -1;
            }
            return 1;
        });
        if (recordList.size() > GameConfig.BANQUET_RELATIONSHIP_LIST_MAX) {
            int index = recordList.size() - 1;
            for (; index >= GameConfig.BANQUET_RELATIONSHIP_LIST_MAX; index--) {
                recordList.remove(index);
            }
        }
        BanquetProto.BanquetRelationshipRespMsg.Builder respMsg = CrossBanquetPb.parseBanquetRelationshipRespMsg(recordList);
        YanQuMessage message = YanQuMessageUtils.buildMessage(Protocol.U_BANQUET_CROSS_USER_RELATIONSHIP_GET, respMsg);
        MessageHelper.sendPacket(serverId, userId, message);
    }

    @Override
    public void sendData() {

    }
}
